<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :http-request="httpimg"
    :before-upload="beforeAvatarUpload"
    :on-change="RemoveImg"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="showProgress" type="circle" :percentage="percent.toFixed(0)" class="progress" />
  </el-upload>
</template>

<script>
// 引入必要的COS模块
const COS = require('cos-js-sdk-v5')
// 实例化对象
const cos = new COS({
  SecretId: 'AKIDHNHwNZWDfroWyBF4ey3tToukLgmdFcja', // 身份识别ID
  SecretKey: 'f4E9oEOJzpXzCAtNcb1B6mDOK2VjjU0H' // 身份秘钥
})
export default {
  name: 'UploadImg',
  // 子组件
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      showProgress: false,
      percent: 0
    }
  },
  watch: {
    value() {
      this.imageUrl = this.value
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpimg(res) {
      console.log(res)
      if (res.file) {
        // 显示
        this.showProgress = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'zhengtongxi-1313015808', /* 存储桶 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            // 执行这个自定义事件把url传出去
            this.$emit('get-url', this.imageUrl)
            // 隐藏
            this.showProgress = false
          }
        })
      }
    }
    // RemoveImg() {
    //   this.imageUrl = ''
    // }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>
